package com.jp.vn.main;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.PopupWindow;

public class BetterPopupWindow {
	protected final View anchor;
	private final PopupWindow window;
	private View root;
	int height;
	int width;
	private Drawable background = null;
	@SuppressWarnings("unused")
	private final WindowManager windowManager;

	public BetterPopupWindow(View anchor,int height,int width) {
		this.anchor = anchor;
		this.height = height;
		this.width = width;
		this.window = new PopupWindow(anchor.getContext());

		this.window.setTouchInterceptor(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
					BetterPopupWindow.this.window.dismiss();
					return true;
				}
				return false;
			}
		});

		this.windowManager = (WindowManager) this.anchor.getContext()
				.getSystemService(Context.WINDOW_SERVICE);
		onCreate();
	}

	protected void onCreate() {
	}

	protected void onShow() {
	}
	

	@SuppressWarnings("deprecation")
	private void preShow() {

		if (this.root == null) {
			throw new IllegalStateException(
					"setContentView was not called with a view to display.");
		}
		onShow();

		if (this.background == null) {
			this.window.setBackgroundDrawable(new BitmapDrawable());
		} else {
			this.window.setBackgroundDrawable(this.background);
		}

		this.window.setWidth(width);
		this.window.setHeight(height);
		this.window.setTouchable(true);
		this.window.setFocusable(true);
		this.window.setOutsideTouchable(true);

		this.window.setContentView(this.root);

	}

	public void setBackgroundDrawable(Drawable background) {
		this.background = background;
	}

	public void setContentView(View root,int height,int width) {
		this.root = root;
		this.height = height;
		this.width = width;
		this.window.setContentView(root);
	}

	public void setContentView(int layoutResID,int height) {
		LayoutInflater inflator = (LayoutInflater) this.anchor.getContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.setContentView(inflator.inflate(layoutResID, null),height,width);
	}

	public void setOnDismissListener(PopupWindow.OnDismissListener listener) {
		this.window.setOnDismissListener(listener);
	}

	public void showPopup(int space) {
		this.preShow();
		this.window.setAnimationStyle(R.style.Animations_GrowFromBottom);
		this.window.showAtLocation(this.anchor, Gravity.CENTER_HORIZONTAL|Gravity.BOTTOM, 0, space);
	}

	public void dismiss() {
		this.window.dismiss();
	}
}
